package com.sia.springcloud.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sia.springcloud.mapper.PointMapper;
import com.sia.springcloud.model.Point;
import com.sia.springcloud.protocol.model.ModbusPoint;
import com.sia.springcloud.service.IPointService;
import com.sia.springcloud.result.GridDataResult;
import com.sia.springcloud.result.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Sirius
 * @Date: 2021/12/21 1:20
 * @Description: 通信协议点位服务层接口实现类
 * 主要提供的接口：添加点位、分页查询点位、批量删除点位、设置点位数采状态
 */
@Slf4j
@Service("PointService")
public class PointService extends ServiceImpl<PointMapper, Point> implements IPointService {

    @Resource
    private PointMapper pointMapper;

    /**
     * 添加点位
     *
     * 备注：并没对对点位数据进行检验，例如点位名称可以多个同时为空，但是如果存在点位名称则不能相同
     *
     * @param point
     * @return
     */
    public String insertPoint(Point point) {
        log.info("插入点位：{}", point.toString());

        //查询数据库中是否有相同设备id，相同点位名的设备，如果有则不能插入
        QueryWrapper<Point> pointQueryWrapper = new QueryWrapper<>();
        pointQueryWrapper.eq("device_id", point.getDeviceId());
        pointQueryWrapper.eq("point_name", point.getPointName());
        Integer selectCount = pointMapper.selectCount(pointQueryWrapper);
        if (selectCount > 0) {
            return ResultUtil.createSimpleFailureJson("该变量名称已存在");
        }

        pointMapper.insert(point);

        return ResultUtil.createSimpleSuccessJson("变量添加成功");
    }

    /**
     * 根据设备 分页查询点位
     *
     * @param start
     * @param limit
     * @param deviceId
     * @return
     */
    public String queryPoint(Integer start, Integer limit, String deviceId) {
        log.info("查询点位，deviceId:{}，limit:{}，start:{}", deviceId, limit, start);

        QueryWrapper<Point> pointQueryWrapper = new QueryWrapper<>();
        pointQueryWrapper.eq("device_id", deviceId);
        Integer total = pointMapper.selectCount(pointQueryWrapper);

        Page<Point> pointPage = new Page<>();
        pointPage.setTotal(total);
        pointPage.setCurrent(start);
        pointPage.setSize(limit);


        IPage<Point> pointIPage = pointMapper.selectPage(pointPage, pointQueryWrapper);
        List<Point> pointList = pointIPage.getRecords();

        ArrayList<ModbusPoint> modbusPointList = new ArrayList<>();
        pointList.forEach(point -> {
            modbusPointList.add(ModbusPoint.reconvert(point));
        });

        log.info("ModbusPointList:" + modbusPointList.toString());


        GridDataResult<ModbusPoint> gridDataResult = new GridDataResult<>();
        gridDataResult.setTotal(total);
        gridDataResult.setRoot(modbusPointList);

        return JSON.toJSONString(gridDataResult);
    }


    /**
     * 删除点位
     *
     * @param pointIdList
     * @return
     */
    public String deletePoint(String[] pointIdList) {
        if (pointIdList.length > 0) {
            log.info("删除点位：{}", pointIdList);
        }
        for (int i = 0; i < pointIdList.length; i++) {
            pointMapper.deleteById(Integer.parseInt(pointIdList[i]));
        }
        return ResultUtil.createSimpleSuccessJson("点位信息删除成功");
    }

    /**
     * 修改点位
     *
     * @param point
     * @return
     */
    public String updatePoint(Point point) {
        log.info("更新点位:{}", point.toString());

        QueryWrapper<Point> pointQueryWrapper = new QueryWrapper<>();
        pointQueryWrapper.eq("device_id", point.getDeviceId());
        pointQueryWrapper.eq("point_name", point.getPointName());
        pointQueryWrapper.ne("id", point.getId());

        Integer selectCount = pointMapper.selectCount(pointQueryWrapper);
        if (selectCount > 0) {
            return ResultUtil.createSimpleFailureJson("该变量名称已存在");
        }
        pointMapper.updateById(point);
        return ResultUtil.createSimpleSuccessJson("变量修改成功");
    }

    /**
     * 获取点位表格格式
     */
    public String tableStructure() {


        // 1.pointName属性
        Map<String,String> pointNameMap1 = new HashMap<>();
        pointNameMap1.put("message", "不允许为空");
        pointNameMap1.put("required", "true");
        Map<String,String> pointNameMap2 = new HashMap<>();
        pointNameMap2.put("pattern", "^[a-z0-9A-Z]+$");
        pointNameMap2.put("type", "string");
        pointNameMap2.put("message", "只能为字母或字母+数字组合");
        List<Map> pointNameValidate = new ArrayList<>();
        pointNameValidate.add(pointNameMap1);
        pointNameValidate.add(pointNameMap2);


        HashMap<String,Object> pointName = new HashMap<>();
        pointName.put("prop", "pointName");
        pointName.put("label", "点位名称");
        pointName.put("type", "Input");
        pointName.put("validate", pointNameValidate);


        // 2.frequency属性
        Map<String,String> frequencyMap1 = new HashMap<>();
        frequencyMap1.put("message", "不允许为空");
        frequencyMap1.put("required", "true");
        Map<String,String> frequencyMap2 = new HashMap<>();
        frequencyMap2.put("pattern", "^(([0-9])|([1-9]+[0-9]*))$");
        frequencyMap2.put("type", "string");
        frequencyMap2.put("message", "必须为整数");
        List<Map> frequencyValidate = new ArrayList<>();
        frequencyValidate.add(frequencyMap1);
        frequencyValidate.add(frequencyMap2);


        HashMap<String,Object> frequency = new HashMap<>();
        frequency.put("prop", "frequency");
        frequency.put("label", "频率");
        frequency.put("type", "Input");
        frequency.put("validate", frequencyValidate);


        // 3.functionCode属性
        Map<String,Object> functionCodeMap1 = new HashMap<>();
        functionCodeMap1.put("name", "1");
        functionCodeMap1.put("sign", 1);
        Map<String,Object> functionCodeMap2 = new HashMap<>();
        functionCodeMap2.put("name", "2");
        functionCodeMap2.put("sign", 2);
        Map<String,Object> functionCodeMap3 = new HashMap<>();
        functionCodeMap3.put("name", "3");
        functionCodeMap3.put("sign", 3);
        Map<String,Object> functionCodeMap4 = new HashMap<>();
        functionCodeMap4.put("name", "4");
        functionCodeMap4.put("sign", 4);
        List<Map> functionCodeOptions = new ArrayList<>();
        functionCodeOptions.add(functionCodeMap1);
        functionCodeOptions.add(functionCodeMap2);
        functionCodeOptions.add(functionCodeMap3);
        functionCodeOptions.add(functionCodeMap4);


        HashMap<String,Object> functionCode = new HashMap<>();
        functionCode.put("prop", "functionCode");
        functionCode.put("options", functionCodeOptions);
        functionCode.put("label", "功能码");
        functionCode.put("type", "Select");


        // 4.slaveId属性
        Map<String,String> slaveIdMap1 = new HashMap<>();
        slaveIdMap1.put("message", "不允许为空");
        slaveIdMap1.put("required", "true");
        Map<String,String> slaveIdMap2 = new HashMap<>();
        slaveIdMap2.put("pattern", "^(([0-9])|([1-9]+[0-9]*))$");
        slaveIdMap2.put("type", "string");
        slaveIdMap2.put("message", "必须为整数");
        Map<String,String> slaveIdMap3 = new HashMap<>();
        slaveIdMap3.put("min", "0");
        slaveIdMap3.put("max", "65535");
        slaveIdMap3.put("message", "必须为0-65535之间的整数");
        List<Map> slaveIdValidate = new ArrayList<>();
        slaveIdValidate.add(slaveIdMap1);
        slaveIdValidate.add(slaveIdMap2);
        slaveIdValidate.add(slaveIdMap3);


        HashMap<String,Object> slaveId = new HashMap<>();
        slaveId.put("prop", "slaveId");
        slaveId.put("label", "从站");
        slaveId.put("type", "Input");
        slaveId.put("validate", slaveIdValidate);


        // 5.offset属性
        Map<String,String> offsetMap1 = new HashMap<>();
        offsetMap1.put("message", "不允许为空");
        offsetMap1.put("required", "true");
        Map<String,String> offsetMap2 = new HashMap<>();
        offsetMap2.put("pattern", "^(([0-9])|([1-9]+[0-9]*))$");
        offsetMap2.put("type", "string");
        offsetMap2.put("message", "必须为整数");
        Map<String,String> offsetMap3 = new HashMap<>();
        offsetMap3.put("min", "0");
        offsetMap3.put("max", "65535");
        offsetMap3.put("message", "必须为0-65535之间的整数");
        List<Map> offsetValidate = new ArrayList<>();
        offsetValidate.add(offsetMap1);
        offsetValidate.add(offsetMap2);
        offsetValidate.add(offsetMap3);


        HashMap<String,Object> offset = new HashMap<>();
        offset.put("prop", "offset");
        offset.put("label", "起始地址");
        offset.put("type", "Input");
        offset.put("validate", offsetValidate);


        // 6.length属性
        Map<String,String> lengthMap1 = new HashMap<>();
        lengthMap1.put("message", "不允许为空");
        lengthMap1.put("required", "true");
        Map<String,String> lengthMap2 = new HashMap<>();
        lengthMap2.put("pattern", "^(([0-9])|([1-9]+[0-9]*))$");
        lengthMap2.put("type", "string");
        lengthMap2.put("message", "必须为整数");
        Map<String,String> lengthMap3 = new HashMap<>();
        lengthMap3.put("min", "0");
        lengthMap3.put("max", "65535");
        lengthMap3.put("message", "必须为0-65535之间的整数");
        List<Map> lengthValidate = new ArrayList<>();
        lengthValidate.add(lengthMap1);
        lengthValidate.add(lengthMap2);
        lengthValidate.add(lengthMap3);


        HashMap<String,Object> length = new HashMap<>();
        length.put("prop", "length");
        length.put("label", "长度");
        length.put("type", "Input");
        length.put("validate", lengthValidate);


        // 7.type属性
        Map<String,String> typeMap1 = new HashMap<>();
        typeMap1.put("name", "bit");
        typeMap1.put("sign", "bit");
        Map<String,String> typeMap2 = new HashMap<>();
        typeMap2.put("name", "char");
        typeMap2.put("sign", "char");
        Map<String,String> typeMap3 = new HashMap<>();
        typeMap3.put("name", "short");
        typeMap3.put("sign", "short");
        Map<String,String> typeMap4 = new HashMap<>();
        typeMap4.put("name", "int");
        typeMap4.put("sign", "int");
        Map<String,String> typeMap5 = new HashMap<>();
        typeMap5.put("name", "real");
        typeMap5.put("sign", "real");
        Map<String,String> typeMap6 = new HashMap<>();
        typeMap6.put("name", "smallshort");
        typeMap6.put("sign", "smallshort");
        Map<String,String> typeMap7 = new HashMap<>();
        typeMap7.put("name", "smallint");
        typeMap7.put("sign", "smallint");
        Map<String,String> typeMap8 = new HashMap<>();
        typeMap8.put("name", "smallreal");
        typeMap8.put("sign", "smallreal");
        List<Map> typeOptions = new ArrayList<>();
        typeOptions.add(typeMap1);
        typeOptions.add(typeMap2);
        typeOptions.add(typeMap3);
        typeOptions.add(typeMap4);
        typeOptions.add(typeMap5);
        typeOptions.add(typeMap6);
        typeOptions.add(typeMap7);
        typeOptions.add(typeMap8);


        HashMap<String,Object> type = new HashMap<>();
        type.put("prop", "typeStr");
        type.put("options", typeOptions);
        type.put("label", "类型");
        type.put("type", "Select");


        //equipmentForm：把上面的属性信息包装到一个map中
        List<Map> tableData = new ArrayList<>();
        tableData.add(pointName);
        tableData.add(frequency);
        tableData.add(functionCode);
        tableData.add(slaveId);
        tableData.add(offset);
        tableData.add(length);
        tableData.add(type);


        Map<String,String> tableMap1 = new HashMap<>();
        tableMap1.put("width", "60");
        tableMap1.put("type", "selection");
        tableMap1.put("align", "center");
        Map<String,String> tableMap2 = new HashMap<>();
        tableMap2.put("title", "点位名称");
        tableMap2.put("align", "center");
        tableMap2.put("key", "pointName");
        Map<String,String> tableMap3 = new HashMap<>();
        tableMap3.put("title", "频率");
        tableMap3.put("align", "center");
        tableMap3.put("key", "frequency");
        Map<String,String> tableMap4 = new HashMap<>();
        tableMap4.put("title", "功能码");
        tableMap4.put("align", "center");
        tableMap4.put("key", "functionCode");
        Map<String,String> tableMap5 = new HashMap<>();
        tableMap5.put("title", "从站");
        tableMap5.put("align", "center");
        tableMap5.put("key", "slaveId");
        Map<String,String> tableMap6 = new HashMap<>();
        tableMap6.put("title", "起始地址");
        tableMap6.put("align", "center");
        tableMap6.put("key", "offset");
        Map<String,String> tableMap7 = new HashMap<>();
        tableMap7.put("title", "长度");
        tableMap7.put("align", "center");
        tableMap7.put("key", "length");
        Map<String,String> tableMap8 = new HashMap<>();
        tableMap8.put("title", "类型");
        tableMap8.put("align", "center");
        tableMap8.put("key", "typeStr");
        List<Map> tableStyle = new ArrayList<>();
        tableStyle.add(tableMap1);
        tableStyle.add(tableMap2);
        tableStyle.add(tableMap3);
        tableStyle.add(tableMap4);
        tableStyle.add(tableMap5);
        tableStyle.add(tableMap6);
        tableStyle.add(tableMap7);
        tableStyle.add(tableMap8);


        Map<String,List> resMap = new HashMap<>();
        resMap.put("tableData", tableData);
        resMap.put("tableStyle", tableStyle);


        log.info("点位表单格式：{}",JSON.toJSONString(resMap));
        return JSON.toJSONString(resMap);

    }


}
